import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USERUID: (state, userId) => {
    state.userId = userId
  }
}

const actions = {
  //用户登录
  login({ commit }, userInfo) {
    //从用户信息中解构出用户名和密码
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      //传递用户名和密码参数
      login({ username: username.trim(), password: password }).then(response => {
        //解构出后端返回的数据
        const { token } = response;
        //将返回的token信息保存到store中
        commit('SET_TOKEN', token);
        //设置token
        setToken(token);
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  //获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response;
        if (!data) {
          reject('认证失败，请尝试重新登录')
        }
        const { roles, name, avatar, introduction, id } = data;
        if (!roles || roles.length <= 0) {
          reject('当前登录账号还未被授予任何角色，请授予角色后尝试重新登录')
        }
        commit('SET_ROLES', roles);
        commit('SET_NAME', name);
        commit('SET_AVATAR', avatar);
        commit('SET_INTRODUCTION', introduction);
        commit('SET_USERUID', id);
        //将权限字段保存到sessionStorage中
        sessionStorage.setItem("codeList",JSON.stringify(roles));
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  //注销登录
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '');
        commit('SET_ROLES', []);
        removeToken();
        resetRouter();
        dispatch('tagsView/delAllViews', null, { root: true });
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '');
      commit('SET_ROLES', []);
      removeToken();
      resolve()
    })
  },

  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token';
    commit('SET_TOKEN', token);
    setToken(token);
    const { roles } = await dispatch('getInfo');
    resetRouter();
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true });
    router.addRoutes(accessRoutes);
    dispatch('tagsView/delAllViews', null, { root: true })
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
